/*
 * xAPthread.java
 *
 * xAP thread
 *
 * Copyright (c) 2009 Daniel Berenguer <dberenguer@usapiens.com>
 *
 * This file is part of the jxAP project.
 *
 * OPNODE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * OPNODE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with canTracer; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * 07/10/09 by Daniel Berenguer : first version
 */

package xAP;


import xAP.xAPtypes.TypeOfElement;

import java.net.*;


public class xAPthread extends Thread
{
   /********************************************************************************************
    * Member variables
    ********************************************************************************************/
    public static boolean bRunXapReader = true;

   /********************************************************************************************
    * xAPreader
    *
    * Class constructor
    ********************************************************************************************/
    public xAPthread()
    {
        // Create table of xAP devices
        drvCore.xAPdevices = new xAPdevBSCtable();
        // Create table of xAP BSC endpoints
        drvCore.bscEndpoints = new xAPBSCtable();
    }
   /********************************************************************************************
    ********************************************************************************************
    *
    * Thread run mewthod
    *
    ********************************************************************************************
    ********************************************************************************************/
    @Override@SuppressWarnings("static-access")
    public void run()
    {
        drvCore.xAP_Port = drvCore.xAP_DefPort;

        while(true)
        {
            try
            {
                // Setup UDP socket
                drvCore.socket = new DatagramSocket(drvCore.xAP_Port);
                break;
            }
            catch (Exception e)
            {
                if (drvCore.xAP_Port == drvCore.xAP_DefPort)
                {
                    drvCore.xAP_Port = drvCore.xAP_MinPort;
                }
                else if (drvCore.xAP_Port < drvCore.xAP_MaxPort)
                    drvCore.xAP_Port++;
                else
                {
                    System.out.println("Unable to connect to a valid UDP port");
                    System.exit(1);
                }
            }
        }

        try
        {
            // Datagram packet
            DatagramPacket packet;

            // Program the transmission of a xAP heart-beat every 60 seconds
            new xAPhbeatScheduler(60);

            // 3-sec delay
            this.sleep(3000);

            // Query xAP BSC data
            queryBSCdata();

            // Start UDP reader
            while(bRunXapReader)
            {
                while(drvCore.xAP_Run == false)
                {
                    this.sleep(5000);
                }

                byte[] buf = new byte[1024];
                packet = new DatagramPacket(buf, buf.length);

                try
                {
                    // Read UDP message
                    drvCore.socket.receive(packet);
                }
                catch (Exception e)
                {
                    continue;
                }

                String received = new String(packet.getData());

                // Process common data
                xAPmessage xAPmess = new xAPmessage(received);

                // Process Body data
                if (xAPmess.xClass.compareToIgnoreCase("xAPBSC.event") == 0 ||
                    xAPmess.xClass.compareToIgnoreCase("xAPBSC.info") == 0)
                {
                    // Update table of BSC devices from xAP message
                    drvCore.xAPdevices.updateTableFromMessage(xAPmess);
                    // Create xAP BSC message from generic xAP message
                    xAPBSCmessage xAPBSCmess = new xAPBSCmessage(xAPmess);
                     // Upate table of endpoint
                    if (drvCore.bscEndpoints.updateTableFromMessage(xAPBSCmess) == true)
                    {
                        // Get VM element
                        xAPelement xElement = drvCore.getFirstElementFromSource(xAPBSCmess.source);

                        while(xElement != null)
                        {
                            TypeOfElement type = xElement.getType();

                            // Send new value to the VM element, depending on the expected data type
                            switch(type)
                            {
                                case BSC_INPUT_STA:
                                    xElement.SendValue(xAPBSCmess.state);
                                    break;
                                case BSC_INPUT_NUM:
                                    if (xAPBSCmess.level == null)
                                        xElement.SendValue(xAPBSCmess.text);
                                    else
                                        xElement.SendValue(xAPBSCmess.level);
                                    break;
                                default:
                                    break;
                            }

                            xElement = drvCore.getNextElementFromSource(xAPBSCmess.source);
                        }
                    }
                }
            }
            // Close UDP socket
            drvCore.socket.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
   /********************************************************************************************
    * queryBSCdata
    *
    * Send xAP BSC query to all devices
    *
    ********************************************************************************************/
    private void queryBSCdata()
    {
        xAPBSCquery query = new xAPBSCquery(">:>");
        query.send();
    }
}
